package rabbitmq

import (
	"context"
	"log"

	amqp "github.com/rabbitmq/amqp091-go"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Panicf("%s: %s", msg, err)
	}
}

func SendExchange() {
	// exhange不用声明吗？直接用
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	ch.ExchangeDeclare(
		"material.main",
		"direct", // type
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)

	body := "Hello World!"
	// 找不到路径的消息，应该会直接丢弃
	routeKeys :=[3]string{"factory_5510","factory_5560","factory_5590"}
	for i := 0; i < 1000; i++ {

		err = ch.PublishWithContext(
			context.Background(),
			"material.main",     // exchange
			routeKeys[i%3], // routing key
			false,  // mandatory
			false,  // immediate
			amqp.Publishing{
				ContentType: "text/plain",
				Body:        []byte(body),
			})
	}
	failOnError(err, "Failed to publish a message")
	log.Printf(" [x] Sent %s\n", body)
}


func SendQueue() {
	// "/"就是数据库名,amqp默认的
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()
	// 这个channel可以干的事情
	q, err := ch.QueueDeclare(
		"hello", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	failOnError(err, "Failed to declare a queue")
	// 没有exchange，直接像队列发送，可以理解为使用了""空
	body := "Hello World!"
	for i := 0; i < 1000; i++ {
		err = ch.Publish(
			"",     // exchange
			q.Name, // routing key
			false,  // mandatory
			false,  // immediate
			amqp.Publishing{
				ContentType: "text/plain",
				Body:        []byte(body),
			})
	}
	failOnError(err, "Failed to publish a message")
	log.Printf(" [x] Sent %s\n", body)
}
